import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.scss']
})
export class GamelistComponent {

  GameList:any[] = []
  searchText:string = ""
  showDelete:boolean = false;
  deleteCount:number = 0;
  constructor(private router:Router){
    this.refresh();
  }

  search(ev?:Event){
    if(ev){
      if((ev as any).code != "Enter") return
    }
    // where={"isDeleted":false,"name":{"$regex":"${this.searchText}"}}
    let searchParams = `,"name":{"$regex":"${this.searchText}"}`
    this.getGameList(searchParams)
  }
  refresh(){
    this.getGameList();
    this.getDeleteCount();
  }
  addNewGame(){
    this.router.navigate(["/game/edit"],{
      queryParams:{
        new:true        
      }
    })
  }
  onShowDelete(){
    console.log("onShowDelete")
    this.showDelete=!this.showDelete
    this.refresh()
  }
  async getDeleteCount(){
    let url = `http://metapunk.cn:9999/parse/classes/Game?where={"isDeleted":true}&count=1&limit=0`

    let result = await fetch(url, {
      "headers": {
        "x-parse-application-id": "dev"
      },
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });
    let data = await result.json();
    this.deleteCount = data.count || 0
  }
  async getGameList(searchParams=""){
    let url = "http://metapunk.cn:9999/parse/classes/Game?"

    // 拼接排序条件
    let paramsOrder = `order=-score`
    url += paramsOrder

    // 拼接匹配条件
    let paramsWhere
    if(!this.showDelete){
      paramsWhere = `where={"isDeleted":false${searchParams}}`
      url += "&" + paramsWhere
    }else{
      paramsWhere = `where={"isDeleted":true${searchParams}}`
      url += "&" + paramsWhere
    }

    let result = await fetch(url, {
      "headers": {
        "x-parse-application-id": "dev"
      },
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });
    let data = await result.json();
    this.GameList = data.results;

    return
    // 测试数据
  }

  async deleteGame(game:any,isRestore:boolean=false){
    let isDeleted = true
    if(isRestore==true){
      isDeleted = false
    }
    // 发送HTTP请求，将isDeleted字段更新为true;
    let objectId = game.objectId
    if(objectId){
      let response = await fetch(`http://metapunk.cn:9999/parse/classes/Game/${objectId}`, {
        "headers": {
          "content-type": "text/plain;charset=UTF-8",
          "x-parse-application-id": "dev"
        },
        "body": `{"isDeleted":${isDeleted}}`,
        "method": "PUT",
        "mode": "cors",
        "credentials": "omit"
      });
      let data = await response.json();
      // 成功删除时，HTTP网络请求返回：{"updatedAt":"2023-01-04T08:29:35.195Z"}
      if(data?.updatedAt){
        // 内存变量删除该项
        let idx = this.GameList.findIndex(item=>item.name==game.name)
        this.GameList.splice(idx,1)
        if(isDeleted){
          this.deleteCount ++;
        }else{
          this.deleteCount --;
        }
      }
      
    }
    return
  }
  editGame(game:any){
    console.log(game)


  }
}
